#! /usr/bin/ruby -w
#
# Mock central server for Bliss project (SIGL p2007-p2008 @ INSIA).
# Stops cleanly on SIGINT (Ctrl+C).  Use to test agent-originating
# notifications.
#
# @author Christophe Porteneuve [tdd@insia.org]
# @since  2007.06.01 10:55
# @latest 2007.06.04 17:54

require 'webrick'

incidents = []
idGen = 0

server = WEBrick::HTTPServer.new :Port => 3000

module WEBrick
  class HTTPRequest
    def post?
      request_method.downcase == 'post'
    end

    def put?
      request_method.downcase == 'put' or post? && query['_method'].downcase == 'put'
    end
  end
end

server.mount_proc '/incidents' do |req, res|
  peer = req.peeraddr[3]
  if req.path_info.empty? && req.post?
    puts "#{peer} reports an incident"
    puts 'Kind: ' + req.query['kind']
    puts 'Data: ' + req.query['data']
    incidents << { :kind => req.query['kind'], :data => req.query['data'], :id => (idGen += 1) }
    res.status = 201
    res['Location'] = req.request_uri.to_s + '/' + incidents.last[:id].to_s
  elsif req.path_info =~ %r{/(\d+)$} && req.put?
    puts "#{peer} reports an incident resolution"
    puts 'ID: ' + $1
    incidents.delete_if { |i| i[:id] == $1.to_i }
    puts "#{incidents.size} incident(s) remaining."
    res.status = 200
  else
    STDERR.puts "Invalid request from #{peer}: #{req.path}"
  end
end

trap('SIGINT') { server.shutdown }
server.start
